package com.stable.actor.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 稳定的网络服务器 - 处理远程Actor通信
 */
public class NetworkServer {
    private ServerSocket serverSocket;
    private final int port;
    private final Map<String, ClientSession> clients = new ConcurrentHashMap<>();
    private final ExecutorService acceptorService = Executors.newSingleThreadExecutor();
    private final ExecutorService workerService = Executors.newFixedThreadPool(10);
    private final AtomicInteger connectionId = new AtomicInteger(0);
    private volatile boolean running = false;

    private MessageHandler messageHandler;

    public interface MessageHandler {
        void onMessage(String clientId, Object message, String senderPath);
        void onClientConnected(String clientId, String remoteAddress);
        void onClientDisconnected(String clientId);
    }

    public NetworkServer(int port) {
        this.port = port;
    }

    public void setMessageHandler(MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    public void start() throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setReuseAddress(true);
        running = true;

        acceptorService.submit(this::acceptConnections);
        System.out.println("✅ 网络服务器启动在端口: " + port);
    }

    private void acceptConnections() {
        while (running) {
            try {
                Socket clientSocket = serverSocket.accept();
                String clientId = "client-" + connectionId.incrementAndGet();
                String remoteAddress = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();

                ClientSession session = new ClientSession(clientId, clientSocket, remoteAddress);
                clients.put(clientId, session);
                session.start();

                if (messageHandler != null) {
                    messageHandler.onClientConnected(clientId, remoteAddress);
                }

                System.out.println("✅ 客户端连接: " + clientId + " from " + remoteAddress);

            } catch (IOException e) {
                if (running) {
                    System.err.println("❌ 接受连接失败: " + e.getMessage());
                }
            }
        }
    }

    public void sendToClient(String clientId, Object message) {
        ClientSession session = clients.get(clientId);
        if (session != null) {
            session.send(message);
        }
    }

    public void stop() {
        running = false;

        // 关闭所有客户端连接
        for (ClientSession session : clients.values()) {
            session.close();
        }
        clients.clear();

        // 关闭线程池
        acceptorService.shutdown();
        workerService.shutdown();

        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            // 忽略关闭异常
        }

        System.out.println("🛑 网络服务器已停止");
    }

    private class ClientSession {
        private final String clientId;
        private final Socket socket;
        private final String remoteAddress;
        private volatile boolean connected = true;

        public ClientSession(String clientId, Socket socket, String remoteAddress) {
            this.clientId = clientId;
            this.socket = socket;
            this.remoteAddress = remoteAddress;
        }

        public void start() {
            workerService.submit(this::readMessages);
        }

        private void readMessages() {
            try (ObjectInputStream input = new ObjectInputStream(socket.getInputStream())) {
                while (connected && !socket.isClosed()) {
                    try {
                        Object message = input.readObject();
                        if (messageHandler != null) {
                            // 这里可以解析发送者信息
                            messageHandler.onMessage(clientId, message, "remote-sender");
                        }
                    } catch (EOFException e) {
                        break; // 连接关闭
                    } catch (ClassNotFoundException e) {
                        System.err.println("❌ 消息反序列化失败: " + e.getMessage());
                    }
                }
            } catch (IOException e) {
                if (connected) {
                    System.err.println("❌ 读取客户端消息失败: " + e.getMessage());
                }
            } finally {
                close();
                clients.remove(clientId);
                if (messageHandler != null) {
                    messageHandler.onClientDisconnected(clientId);
                }
                System.out.println("🚪 客户端断开: " + clientId);
            }
        }

        public void send(Object message) {
            if (!connected) return;

            try (ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream())) {
                output.writeObject(message);
                output.flush();
            } catch (IOException e) {
                System.err.println("❌ 发送消息到客户端失败: " + clientId);
                close();
            }
        }

        public void close() {
            connected = false;
            try {
                socket.close();
            } catch (IOException e) {
                // 忽略关闭异常
            }
        }
    }
}
